/*
 * Copyright 2010 Gal Dolber.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.guit.demo.client.dynamic;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.inject.Inject;

import com.guit.client.GuitPresenter;
import com.guit.client.ViewProperties;
import com.guit.client.ViewType;
import com.guit.client.apt.GwtPresenter;
import com.guit.client.binder.Attribute;
import com.guit.client.binder.GuitBinder;
import com.guit.client.binder.ViewField;
import com.guit.client.binder.ViewHandler;
import com.guit.client.binder.ViewInitializer;
import com.guit.client.binder.contributor.HasAttribute;
import com.guit.client.binder.contributor.RunAsync;
import com.guit.client.place.Place;
import com.guit.demo.client.common.HasInnerHTML;
import com.guit.demo.client.dynamic.DynamicPresenter.DynamicBinder;
import com.guit.demo.client.main.MainPresenter;

import java.util.ArrayList;

@RunAsync
@GwtPresenter(placeName = "dynamic")
@ViewProperties(type = ViewType.WIDGET)
public class DynamicPresenter extends GuitPresenter<DynamicBinder> implements Place<Void> {

  public interface DynamicBinder extends GuitBinder<DynamicPresenter> {
  }

  final ArrayList<String> list = new ArrayList<String>();

  private final MainPresenter hasContent;

  @ViewField
  DynamicConstants constants;

  @ViewField
  HasInnerHTML table;

  @Inject
  public DynamicPresenter(MainPresenter hasContent) {
    this.hasContent = hasContent;
  }

  @Override
  public void go(Void data) {
    hasContent.setContent(getView(), 1);
  }

  private void render() {
    StringBuilder sb = new StringBuilder();
    sb.append("<table>");
    for (String item : list) {
      sb.append("<tr>");

      sb.append("<td>");
      sb.append(item);
      sb.append("</td>");

      sb.append("<td>");
      sb.append("<button item='" + item + "'>Delete</button>");
      sb.append("</td>");

      sb.append("</tr>");
    }
    sb.append("</table>");
    table.setInnerHTML(sb.toString());
  }

  @ViewHandler(force = true)
  @HasAttribute("item")
  void $click(@Attribute String item) {
    list.remove(item);
    render();
  }

  // An empty field means to add the handler to the view generated Widget
  @ViewHandler(event = ClickEvent.class, force = true, fields = "")
  @HasAttribute("reset")
  @ViewInitializer
  void reset() {
    list.clear();

    // Generate random data
    for (int n = 0; n < 10; n++) {
      list.add(constants.buttonText() + n);
    }
    render();
  }
}
